<template>
  <div class="flex justify-between w-full mt-4 mb-8  sm:flex-col-reverse md:flex-row m-flex-rc">
    <div class=" left-list pt-2 sm:pt-4 md:w-70% sm:w-full ">
        <Carousel />  
      <div class="bg-light-100 shadow-xl rounded-lg opacity-90  mt-4 overflow-hidden">
        <ul class="" 
          v-infinite-scroll="load"
          infinite-scroll-distance="10"
          :infinite-scroll-disabled="disabled"
          v-if="isMounted"   
        >
          <li class="flex justify-end items-center pt-2 sm:pt-4 px-4">
            <el-dropdown @command="handleCommand">
              <span class="flex justify-center items-center el-dropdown-link text-base">    
                排序：{{sorting}} <div class="ml-1 i-carbon-chevron-down"></div>
              </span>
              <template #dropdown>
                <!-- data-cm="最新" -->
                <el-dropdown-menu>
                  <el-dropdown-item command="最新">最新</el-dropdown-item>
                  <el-dropdown-item command="最早">最早</el-dropdown-item>
                  <el-dropdown-item command="热门">热门</el-dropdown-item>
                </el-dropdown-menu>
                
              </template>
            </el-dropdown>
            
          </li>
          <!-- 骨架屏 -->
          <el-skeleton  :loading="skeletonLoading" animated>
            <template #template>
              <li :key="item" v-for="item in PageStep"
                class="article-item py-4 sm:px-8 px-2 divide_b text-left ">
                <!-- 用户信息 -->
                <div class="flex justify-start items-center relative flex-wrap">
                  <div class="mr-2">
                    <el-skeleton-item  variant="text" class="avatar! wh-8!"/>
                  </div>
                  <div><span><el-skeleton-item variant="text" /></span></div>
                  <div class="ml-2">
                    <el-skeleton-item variant="text" class="h-4! w-7!"/>
                  </div>
                  <div class="ml-4">
                    <el-skeleton-item variant="text" class="h-4! w-16!" />
                  </div>            
                  <div
                    class="followBtn!  absolute! right-0 rounded-2  py-1 md:px-5 sm:px-4 px-2 md:text-base! text-sm!"
                    >
                    <el-skeleton-item variant="button" />
                  </div>
                </div>
                <!-- 标题 -->
                <div class="truncate pt-2 text-2xl font-bold  title">
                  <el-skeleton-item   variant="h1"/>
                </div>
                <!-- 内容 -->
                <div class="truncate text-lg content">
                  <el-skeleton-item variant="h3" />
                </div>
                <!-- 图片 -->
                <div class="flex justify-start">
                  <el-skeleton-item v-for="item in 3" :key="item" variant="image"  class="px-1" style="width: 9rem; height: 9rem"/>
                </div>
                
                <div class="flex justify-end opacity-80">
                  <el-skeleton-item variant="text"  class="h-6! w-36!"/>
                </div>
              </li>
              
            </template>
            <!-- 帖子模块 -->
            <template #default>
              <li :key="item._id" v-for="item in articleList?.slice(0,nextPage)"
                class="article-item py-4 sm:px-8 px-2 divide_b text-left ">
                <!-- 用户信息 -->
                <div class="flex justify-start items-center relative flex-wrap">
                  <RouterLink :to="`/accountCenter/postList/${item?.user?._id}`">
                    <div class="mr-2">
                      <img :src="IMG_URL_SERVER+item?.user?.avatar?.url" :alt="item?.user?.avatar?.name" class="avatar wh-8" />
                    </div>
                  </RouterLink>
                  <RouterLink :to="`/accountCenter/postList/${item?.user?._id}`">
                    <div><span class="hover:text-blue-500">{{item?.user?.nickname}}</span></div>
                  </RouterLink>
                  <div class="ml-2">
                    <img class="h-4" :src="IMG_URL_SERVER+item?.user?.level?.url" alt="">
                  </div>
                  <!-- 时间 -->
                  <div class="ml-4 h3 text-sm">{{dateFormat(item?.createdAt)}}</div>
                  <!-- //关注 -->
                  <div v-show="!(followingList?.includes(item?.user?._id) || (item?.user?._id == user?._id))"
                    @click="addFollowing(item.user._id)" disabled="true" class="followBtn transition duration-300  absolute right-0 bg-blue-500 text-light-50 hover:bg-blue-400 rounded-2 cursor-pointer
                          py-1 md:px-5 sm:px-4 px-2 md:text-base text-sm">
                    关注
                  </div>
                </div>
                <!-- 标题 -->
                <RouterLink :to="`/article/${item._id}`">
                  <div class="truncate pt-2 text-xl leading-5 font-bold hover:text-blue-500 title">{{item.title}}</div>
                </RouterLink>
                <!-- 内容 -->
                <div class="truncate text-base leading-4 content">{{item.text}}</div>
                <!-- 图片 -->
                <div class="flex justify-start">
                  <template v-for="img,index in item.images.slice(0,3)" :key="img._id">

                    <el-image class="px-1" style="width: 9rem; height: 9rem" :src="IMG_URL_SERVER+img.url"
                      :preview-src-list="item.images.slice(0,3).map((val:any)=> IMG_URL_SERVER+val.url)" :initial-index="index"
                      :alt="img.name" fit="cover" />
                  </template>
              
                </div>
              
                <div class="flex justify-end opacity-80">
                  <div class="flex items-center">
                    <div class="wh-6 mx-2 i-carbon-view"></div>
                    <span>{{item.read}}</span>
                  </div>
                  <div class="flex items-center">
                    <RouterLink :to="`/article/${item._id}#reply`">
                      <div class="wh-6 mx-2 cursor-pointer i-carbon-chat"></div>
                    </RouterLink>
                    <span>{{item.comments}}</span>
                  </div>
                  <div class="flex items-center">
                    <template v-if="praiseList?.includes(item._id)">
                      <div :data-flag="praiseList?.includes(item._id)" @click="addLiking(item._id,$event)"
                        :class="`wh-6 mx-2 cursor-pointer bg-sky-500 i-carbon-thumbs-up-filled`">
                      </div>
                      <span ref="count" :data-count="item._id">{{item.praise}}</span>
                    </template>
                    <template v-else>
                      <div :data-flag="praiseList?.includes(item._id)" @click="addLiking(item._id,$event)"
                        :class="`wh-6 mx-2 cursor-pointer i-carbon-thumbs-up`">
                      </div>
                      <span ref="count" :data-count="item._id">{{item.praise}}</span>
                    </template>
                  </div>
                </div>
              
              </li>
            </template>
          </el-skeleton>
          
        </ul>
        <template v-if="articleList?.length === 0">
          <el-empty class=" min-h-140" description="暂时还没有贴子哦" />
        </template>
        <template v-else>
          <div v-if="loading" class="  h-20 flex justify-center items-center">
          <div class="animate-spin mr-1 bg-blue-500 wh-8! i-carbon-restart "></div>
          <span class="text-2xl leading-20">
            加载中...
          </span>
          </div >
          <div v-if="noMore" class=" h-20 text-center">
          <span class="text-2xl leading-20 ">
            没有更多数据了
          </span>
          </div >
        </template>
      </div>
    </div>

    <div class=" md:w-27% md:my-4 sm:w-full right-option ">
      <div class="sticky top-1rem">
        <div class=" relative card w-full md:py-16 flex justify-center left-bar bg-white  sm:py-0 opacity-90 rounded-lg">
          <RouterLink custom :to="`/bbs/newArticle`" v-slot="{navigate}">
            <button  @click="posting(navigate)" class="lg:text-lg md:text-md release-btn flex justify-around items-center">
              <div class="i-carbon-edit mr-2"></div>
              <span class=" text-yellow-900 font-medium mr-2 ">发布帖子</span>
              <div class="i-carbon-chevron-right"></div>
            </button>
          </RouterLink>
          <img ref="runDom" class=" absolute top-0 left-0 wh-16 md:block hidden" :src="run" alt="">
        </div>
        <div class="card mb-hidden md:w-full md:my-6 md:py-2 md:bg-white md:px-2 opacity-90 rounded-lg">
        <!--发来的帖子列表的浏览+评论的总数排下去-->
          <h1 class="h1">热门推荐</h1>
          <div class="flex flex-col justify-center items-start ">
            <div v-for="item in hotList" class="flex justify-start items-center hover:text-blue-500 cursor-pointer hover:underline truncate w-full mb-1">
              <!-- 骨架屏 -->
              <el-skeleton :loading="skeletonLoading" animated> 
                <template #template>
                  <div class="flex justify-start ">
                    <el-skeleton-item v-for="item in 1" :key="item" variant="image" class="mr-2 border recommend-img"/>
                    <div class="flex flex-col justify-around w-full">
                      <el-skeleton-item variant="h1" />
                      <el-skeleton-item variant="h1" />
                    </div>
                    
                  </div>
                </template>
                <template #default>
                  <!-- 图片 -->
                  <template v-if="item?.images?.length !== 0">
                    <el-image v-for="img,index in item.images.slice(0,1)" :key="img._id" class="mr-2 border recommend-img"
                      :src="IMG_URL_SERVER+img.url" :preview-src-list="item.images.slice(0,3).map((val:any)=> IMG_URL_SERVER+val.url)"
                      :initial-index="index" :alt="img.name" fit="cover" />
                  </template>
                  <template v-else>
                    <img class="wh-16 mr-2" :src="kongbai" alt="">
                  </template>
                  
                  <RouterLink :to="`/article/${item._id}`" class="truncate overflow-hidden">
                    <div class="truncate w-full">{{item.title}}</div>
                  </RouterLink>
                </template>
              </el-skeleton>
              

            </div>    
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { fetchFollowingList, fetchAddFollowing, fetchLikingTopic, fetchUnLikingTopic, fetchLikingTopicList, fetchTopicList, fetchEarlyTopicList, fetchHotTopicList,fetchHottestTopicList } from "@/server";
import { IMG_URL_SERVER } from "@/config"
import { dateFormat } from "@/utils"
import kongbai from "@/assets/kongbai.webp"
import  run  from "@/assets/run2.gif"
import { gsap } from "gsap";

//router
const route = useRoute()
//文章store
const articleStore = useArticleStore();
const { articleList }  = storeToRefs<any>(articleStore)
//现在登录用户store
const authStore = useAuthStore()
const {user}  = storeToRefs(authStore)
//工具store
const utilsStore = useUtilsStore()
const { skeletonLoading } = storeToRefs(utilsStore) //骨架屏渲染
//reload 重载
const { reloadFlag,handleReload } = inject<any>('reload')
//关注列表id
const followingList = ref()
//点赞列表id
const praiseList = ref()
//热门推荐List
const hotList:any = ref([])
//刷新等待时间
const loadingTime = 600 
//runDom
const runDom = ref()






//排序
const sorting = ref('最新')
//最早最新热门
const handleCommand = (command:string) => {
  skeletonLoading.value = true
  sorting.value = command
  if(sorting.value==='最新'){
    fetchTopicList(()=>true).then((data)=>{
      articleList.value = data
      setTimeout(() => {
        skeletonLoading.value = false
      }, loadingTime)

    })
  }
  if(sorting.value==='最早'){
    fetchEarlyTopicList(()=>true).then((data)=>{
      articleList.value = data
      setTimeout(() => {
        skeletonLoading.value = false
      }, loadingTime)
      
    })
  }
  if(sorting.value==='热门'){
    fetchHotTopicList(()=>true).then((data)=>{
      articleList.value = data
      setTimeout(() => {
        skeletonLoading.value = false
      }, loadingTime)

    })
  }
}




//点击发帖
const posting = (n:any)=>{
  //保护条款
  if(authStore.isAuthenticated){
    n()
  }else{
    utilsStore.dialogTableVisible = true   
  }
}



//点击关注
const addFollowing = (id:string)=>{
  //保护条款
  if(!authStore.isAuthenticated){
    utilsStore.dialogTableVisible = true 
    return false;
  }
  document.querySelectorAll('.followBtn').forEach((el:any)=>{
    el.style.opacity = '0'
    el.style.pointerEvents = 'none' //css属性禁止点击事件
  })
  fetchAddFollowing(id,()=>{
    handleReload(500)
  })
  
}

//点击点赞
const count = ref()
const addLiking = (id:any,e:any)=>{
  //保护条款
  if(!authStore.isAuthenticated){
    utilsStore.dialogTableVisible = true 
    return false;
  }
  let span = count.value.find(function(val:any){
    return val.dataset.count === id; //条件，返回真假
  })
  
  if(e.target.dataset?.flag === 'false'){   
    fetchLikingTopic(id,()=>{
      e.target.dataset.flag = 'true'
      span.textContent = Number(span.textContent)+1
      e.target.classList.add("i-carbon-thumbs-up-filled","bg-sky-500")
      e.target.classList.remove("i-carbon-thumbs-up")
      return true;
    })
  }else{
    fetchUnLikingTopic(id,()=>{
      e.target.dataset.flag = 'false'
      span.textContent = Number(span.textContent)-1
      e.target.classList.remove("i-carbon-thumbs-up-filled","bg-sky-500")
      e.target.classList.add("i-carbon-thumbs-up")
      return true;
    })
  } 
}

//加载更多
let PageStep:number = 5 //跳过
let nextPage = ref(PageStep)
const loading = ref(false)
const noMore = computed(() => nextPage.value >= (articleList.value?.length))
const disabled = computed(() => loading.value || noMore.value )
const load = () => {
  loading.value = true
  setTimeout(() => {
    nextPage.value += PageStep 
    loading.value = false
  }, loadingTime)
}

// const clickLoad = ()=>{
//   clkLoad.value = false
//   window.scrollTo(window.scrollX,window.scrollY-1000)
//   window.scrollTo(window.scrollX,window.scrollY+1000)
// }

//更新时发送fetch
watchEffect(()=>{
  if(reloadFlag.value || route.params.id){
    skeletonLoading.value = true
    //获取关注列表
    fetchFollowingList(user?.value?._id, () => true).then((data:any) => {
        const fmt = data?.map(function (val: any) {
          return val?._id;
        })
        followingList.value = fmt
    }).catch(()=>{})
    
    
    //获取点赞列表
    fetchLikingTopicList(() => true).then((data: any)=>{
      const fmt = data?.map(function(val:any){
        return val._id
      })
      praiseList.value=fmt
    })
    //获取帖子列表
    if(sorting.value==='最新'){
      fetchTopicList(()=>true).then((data)=>{
        articleList.value = data
        setTimeout(() => {
          skeletonLoading.value = false
        }, loadingTime)

      })
    }else if(sorting.value==='最早'){
      fetchEarlyTopicList(()=>true).then((data)=>{
        articleList.value = data
        setTimeout(() => {
          skeletonLoading.value = false
        }, loadingTime)
      })
    } else if(sorting.value==='热门'){
      fetchHotTopicList(()=>true).then((data)=>{
        articleList.value = data
        setTimeout(() => {
          skeletonLoading.value = false
        }, loadingTime)
      })
    }

    //获取特定热门帖子列表
    fetchHottestTopicList(() => true).then((data) => {
      hotList.value = data.slice(0, 6)
    })

  }

},{flush:'post'})

//解决v-infinite-scroll数据渲染报错
const isMounted = ref(false);
onMounted(() => {
  isMounted.value = true;
  const tl = gsap.timeline({repeat:-1})
  tl.fromTo(runDom.value,{top: 0,rotation:90,},{top:"100%",y:"-100%",duration:2})
    .to(runDom.value, { rotation: 0, duration:1 })
    .to(runDom.value, { left: "100%",x:"-100%", duration: 5 })
    .to(runDom.value, { rotation: -90, duration: 1 })
    .to(runDom.value, { top: 0, y: 0,duration: 2 })
    .to(runDom.value, { rotation: -180, duration: 1})
    .to(runDom.value, { left: 0, x: 0, duration: 5 })
    .to(runDom.value, { rotation: -270, duration: 1 })
});

</script>

<style scoped lang="scss">
.article-item>div{
  padding-top: 0.5rem;
}
.recommend-img{
  // flex-basis:20%;
  height:4rem;
  min-width: 22%;
  div{
    width: 100%;
    height:100%;

  }
  img{
    width:100%;
    height:100%;
    object-fit: cover;
  }
}
.left-bar{
  display: flex;
  justify-content: center;
  align-items:center;
  @media screen and (max-width:768px){
    background-color:rgba(246,246,246,0);
    padding-right: 1rem;
    justify-content: flex-end;
   
  }
  .release-btn{
    
    background-color: #FCD34D;
    padding: 0.7rem 2rem;
    border-radius: 0.5rem;
    font-family: Arial, Helvetica, sans-serif;
    &:hover{
      background-color: #FDE047;
    }
    @media (max-width:768px) {
      padding: 0.3rem 0.44rem;
     
    }
    @media (min-width:768px) and (max-width:1024px) {
      padding: 0.7rem 0.9rem;
    }
    @media (min-width:1024px) and (max-width:1280px) {
      padding: 0.7rem 0.95rem;
    }
  }
}

@media screen and (max-width:768px){
  .mb-hidden{
    display: none;
  }
}
.card{
  box-shadow: 1px 1px 3px rgba(182, 182, 182, 0.6),
  -1px -1px 3px rgba(182, 182, 182, 0.6);
  @media screen and (max-width:768px){
    box-shadow: none;
  }
}


.m-flex-rc{
  @media (max-width:640px) {
    flex-direction: column-reverse;
      .left-list{
        width: 100%;
        font-size: 0.94rem;
      }
  }
}

.article-item{
  @media screen and (min-width:640px) and (max-width:768px){
    font-size: 0.95em;
    .title{
      font-size: 1.4rem;
      line-height: 1.7rem;
      padding-top: 0.3rem;
    }
    .content{
      font-size: 1.1rem;
      line-height: 1.65rem;
      padding-top: 0.3rem;
    }
  }
  @media screen and (max-width:640px){
    font-size: 0.95em;
    .title{
      font-size: 1.3rem;
      line-height: 1.6rem;
      padding-top: 0.25rem;

    }
    .content{
      font-size: 1.1rem;
      line-height: 1.65rem;
      padding-top: 0.25rem;

    }
  }
}
</style>

<route lang="yaml">
meta:
  layout: home
</route>

